// Copyright 2011 Hunter Freyer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package languish.base;

import static languish.base.Operation.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import languish.base.error.AlreadyReducedError;
import languish.base.error.InvalidApplicationException;

public class Reducer {

  private final Map<Integer, NativeFunction> nativeFunctions;

  public Reducer(Map<Integer, NativeFunction> nativeFunctions) {
    this.nativeFunctions = nativeFunctions;
  }

  public Term reduce(Term term) {
    Operation op = term.getOperation();

    if (!Terms.isReducible(term)) {
      throw new AlreadyReducedError(term);
    }

    if (op == APP) {
      Term func = (Term) term.getFirst();
      Term arg = (Term) term.getSecond();

      if (Terms.isReducible(func)) {
        return Terms.app(reduce(func), arg);
      }

      if (func.getOperation() != ABS) {
        throw new InvalidApplicationException(term);
      }

      Term absExp = (Term) func.getFirst();

      return replaceAllReferencesToParam(absExp, 1, arg);
    }

    if (op == NATIVE_APPLY) {
      Integer funcCode = (Integer) term.getFirst();
      List<?> args = term.getArgs().subList(1, term.getArgs().size());

      List<Primitive> reducedArgs = new LinkedList<Primitive>();

      Iterator<?> argIter = args.iterator();
      boolean allReduced = true;

      Term currentArg = null;
      while (argIter.hasNext()) {
        currentArg = (Term) argIter.next();

        if (Terms.isReduced(currentArg)) {
          reducedArgs.add(Terms.termToPrimitive(currentArg));
        } else {
          allReduced = false;
          break;
        }
      }

      if (allReduced) {
        if (!nativeFunctions.containsKey(funcCode)) {
          // TODO(hjfreyer): Make an exception for this
          throw new RuntimeException("Function not supported: " + funcCode);
        }

        return Terms.primitive(
          nativeFunctions.get(funcCode).apply(reducedArgs));
      }

      List<Term> newArgs = new ArrayList<Term>();
      for (Primitive p : reducedArgs) {
        newArgs.add(Terms.primitive(p));
      }

      // currentArg is the first unreduced arg.
      newArgs.add(reduce(currentArg));

      while (argIter.hasNext()) {
        newArgs.add((Term) argIter.next());
      }

      return Terms.nativeApplyList(funcCode, newArgs);
    }

    if (op == IF) {
      Term arg = (Term) term.getFirst();

      if (Terms.isReducible(arg)) {
        return Terms.ifTerm(reduce(arg));
      }

      return arg.getOperation() == Operation.NULL ?
        Terms.FALSE : Terms.TRUE;
    }

    throw new AssertionError();
  }

  public static Term replaceAllReferencesToParam(Term term, int id, Term with) {
    Operation op = term.getOperation();

    if (op == REF) {
      int ref_id = (Integer) term.getFirst();

      return (ref_id == id) ? with : term;
    }

    if (op == ABS) {
      Term subterm = (Term) term.getFirst();
      return Terms.abs(replaceAllReferencesToParam(subterm, id + 1, with));
    }

    if (op == PRIMITIVE) {
      return term;
    }

    if (op == NATIVE_APPLY) {
      int funcCode = (Integer) term.getFirst();

      List<Term> newArgs = new ArrayList<Term>();
      for (Object t : term.getArgs().subList(1, term.getArgs().size())) {
        newArgs.add(replaceAllReferencesToParam((Term) t, id, with));
      }

      return Terms.nativeApplyList(funcCode, newArgs);
    }

    if (op == APP || op == IF || op == NULL) {
      return propagateReplaceReference(term, id, with);
    }

    throw new AssertionError();
  }

  public static Term propagateReplaceReference(Term term, int id, Term with) {
    List<Term> newTerms = new ArrayList<Term>();

    for (Object t : term.getArgs()) {
      newTerms.add(replaceAllReferencesToParam((Term) t, id, with));
    }

    return new Term(term.getOperation(), newTerms);
  }

  public Term reduceCompletely(Term term) {
    while (Terms.isReducible(term)) {
      term = reduce(term);
    }

    return term;
  }
}
